const user_col = require('../../modles/user.js')//生成好的user表
const password_col = require('../../modles/password.js')//生成好的密码表
const crypt = require('../../utils/password.js')//引入封装的加密校验函数
const { v1: uuidv1 } = require('uuid')//自动生成id值
const config = require('../../config.js')//加密参数的配置文件
const task_model = require('../../modles/Task.js')//任务列表
//登录
const login = async (ctx, next) => {
    console.log(ctx.request.body);
    const { account, password } = ctx.request.body
    //在user表中查找是存在
    const user = await user_col.findOne({
        account: account,
    })
    if (!user) {
        ctx.status = 200;
        ctx.body = {
            code: 0,
            msg: '用户不存在'
        }
    }
    //如果用户存在，去密码表找对应的密码
    const userId = user.userId
    const pass = await password_col.findOne({
        userId: userId,
    })
    const result = await crypt.validate(password, pass.hash)
    console.log(result);
    ctx.status = 200;
    if (result) {
            ctx.body = {
                code: 1,
                msg: '登录成功',
                data: user
            }        
    } else {
        ctx.body = {
            code: 0,
            msg: '密码错误',
        }
    }
}
//用户注册
const register = async (ctx, next) => {

    const { account, password } = ctx.request.body
    console.log(account);
    const user = await user_col.findOne({
        account: account,
    })
    if (user) {
        ctx.status = 200;
        ctx.body = {
            code: 0,
            msg: '账号已存在请登录'
        }
        return
    }
    //往数据库植入数据
    let userId = uuidv1()
    const newUser = await user_col.create({
        userId: userId,
        account: account,
    })
    if (newUser) {
        //密码加密后存入密码表
        await crypt.encrypt(password, config.saltTimes).then(async (hash) => {
            const result = await password_col.create({
                userId: userId,
                hash
            })
            // console.log(result);
            if (result) {
                ctx.body = {
                    code: 1,
                    msg: '注册成功',
                    data: {
                        userId: newUser.userId,
                        account: newUser.account
                    }
                }
            } else {
                ctx.body = {
                    code: 0,
                    msg: '注册失败',
                }
            }
        })


    }
}
//修改个人信息
const updatauserinfo = async (ctx, next) => {
    const req = ctx.request.body
    const result = await user_col.updateOne({
        userId: req.userId
    }, req)
    console.log(result);
    if (result.modifiedCount) {
        ctx.body = {
            code: 1,
            msg: '修改成功'
        }
    } else {
        ctx.body = {
            code: 0,
            msg: '修改失败'
        }
    }
}
//发布任务或修改任务
const Taskinfo = async (ctx, next) => {
    if (ctx.request.body.TaskInfo.updata !== 'noupdata') {
        console.log(ctx.request.body);
        let { title, place, price, select, content, currentDate, hours, _id } = ctx.request.body.TaskInfo
        let { userId } = ctx.request.body.TaskInfo.userinfo
        const newTask = await task_model.updateOne({ _id: _id },
            ctx.request.body.TaskInfo)
        console.log(newTask);
        if (newTask) {
            ctx.body = {
                code: 1,
                msg: '修改成功',
                data: {
                    newTask
                }
            }
        }
    } else {
        console.log(ctx.request.body);
        let { title, place, price, select, content, currentDate, hours, userinfo } = ctx.request.body.TaskInfo
        let { userId } = ctx.request.body.TaskInfo.userinfo
        const newTask = await task_model.create({
            userinfo:userinfo,
            userId: userId,
            title: title,
            place,
            price,
            select, content, currentDate, hours, applicants: 'null', status: '0'
        })
        if (newTask) {
            ctx.body = {
                code: 1,
                msg: '发布成功',
                data: {
                    newTask
                }
            }
        }
    }

}
//请求总任务列表
const reqTask = async (ctx, next) => {
    if (ctx.request.body.userId) {
        const reqTask = await task_model.find({
            userId: ctx.request.body.userId,
            status:0
        })
        ctx.body = {
            code: 1,
            msg: '请求用户列表',
            data: {
                reqTask
            }
        }
    } else {
        const reqTask = await task_model.find({ status: 0 })
        ctx.body = {
            code: 1,
            msg: '请求全部列表',
            data: {
                reqTask
            }
        }
    }


}
//删除任务
const delTask = async (ctx, next) => {
    // console.log(ctx.request.body.userId);
    const delTask = await task_model.findOneAndDelete({
        _Id: ctx.request.body.userId
    })
    if (delTask) {
        ctx.body = {
            code: 1,
            msg: '删除成功',
            data: {
                delTask
            }
        }
    } else {
        ctx.body = {
            code: 1,
            msg: '删除失败',
            data: {
                delTask
            }
        }
    }
}
//接取任务
const applicants = async (ctx) => {
    let { ToskID, userId } = ctx.request.body
    // console.log({ToskID,userId});
    const like = await task_model.findOne({ _id: ToskID })
    console.log(like.userId);
    if(like.status != 0){
        ctx.body = {
            code:1,
            msg:'该订单已被人抢走了'
        }
    }
    if (like.userId !== userId) {
        const newTask = await task_model.updateOne({ _id: ToskID },
            { applicants: userId, status: 1 })
        console.log(newTask);
        if (newTask) {
            ctx.body = {
                code: 1,
                msg: '接单成功',
                data: {
                    newTask
                }
            }
        }
    } else {

        ctx.body = {
            code: 1,
            msg: '接单失败，不能接取自己的订单',

        }

    }

}
//请求我的订单
const Myorder = async (ctx) =>{
    console.log(ctx.request.body);
    let applicants= ctx.request.body
    const newTask = await task_model.find(applicants)
    console.log(newTask);
    ctx.body = {
        code:1,
        msg:'请求成功我的订单',
        data:{
            newTask
        }
    }
}
//完成任务
const successtask = async (ctx)=>{
    let success = ctx.request.body
    const newTask = await task_model.updateOne(success.upkey,success.upval)
    ctx.body = {
        code:1,
        msg:'修改成功',
        data:{
            newTask
        }
    }
}

module.exports = {
    login,
    register,
    updatauserinfo,
    Taskinfo,
    reqTask,
    delTask,
    applicants,
    Myorder,
    successtask,
}